<script setup>
import personalCenterService from '@/services/personal-center.service';
import { useAuthStore } from '@/stores/auth';
import { AxiosError } from 'axios';
import { ElMessage, ElForm, ElFormItem, ElInput, ElButton, ElMain, ElContainer } from 'element-plus';
import { onMounted, reactive, ref } from 'vue';
import { useRouter } from 'vue-router';
import authService from '@/services/auth.service';
import { REGEX_PASSWORD } from "@/utils/regexes";
import { Search, Refresh, Plus, Edit, Delete, View, Upload, Download, Share, Close } from "@element-plus/icons-vue";

const router = useRouter();
const authStore = useAuthStore();
const entity = ref({});
const loading = ref(false);
const verifyCodeUrl = ref("");

const formRef = ref();
const rules = reactive({
    oldPassword: [
        {
            validator: (rule, value, callback) => {
                if (!value) {
                    callback(new Error("请输入旧密码"));
                } else {
                    callback();
                }
            },
            trigger: "blur"
        }
    ],
    newPassword: [
        {
            validator: (rule, value, callback) => {
                if (!value) {
                    callback(new Error("请输入新密码"));
                } else if (!REGEX_PASSWORD.test(value)) {
                    callback(
                        new Error("密码格式应为8-18位数字、字母、符号的任意两种组合")
                    );
                } else {
                    callback();
                }
            },
            trigger: "blur"
        }
    ],
    confirmPassword: [
        {
            validator: (rule, value, callback) => {
                if (!value) {
                    callback(new Error("请输入确认密码"));
                } else if (entity.value.newPassword && entity.value.confirmPassword && entity.value.newPassword != entity.value.confirmPassword) {
                    callback(new Error("两次密码输入不一致"));
                } else {
                    callback();
                }
            },
            trigger: "blur"
        }
    ],
    verifyCode: [
        {
            required: true,
            message: '请输入验证码',
            trigger: 'blur'
        },
    ],
});

const save = async () => {
    try {
        loading.value = true;
        await personalCenterService.changePassword(entity.value);
        authStore.unAuthenticate();
        router.push("/login");
        ElMessage({
            message: "保存成功", type: "success"
        });
    } catch (err) {
        if (err instanceof AxiosError) {
            const msg = err.response?.data?.message || err.message;
            ElMessage({ message: msg, type: "error" });
        }
        throw err;
    } finally {
        loading.value = false;
    }
};

const updateVerifyCode = async () => {
    const res = await authService.getVerifyCode();
    verifyCodeUrl.value = `${res.data.data?.image}`;
    entity.value.verifyCodeKey = res.data.data?.key;
}

onMounted(() => {
    entity.value = {};
    updateVerifyCode();
});
</script>

<template>
    <div class="h-full w-full">
        <ElContainer class="flex justify-center">
            <ElMain class="" style="max-width: 460px;">
                <h3 class="text-center">修改密码</h3>
                <ElForm ref="formRef" :model="entity" :rules="rules" label-width="120px" class="form" :inline="false">
                    <ElFormItem prop="oldPassword" label="旧密码">
                        <ElInput clearable show-password v-model="entity.oldPassword" />
                    </ElFormItem>
                    <ElFormItem prop="newPassword" label="新密码">
                        <ElInput clearable show-password v-model="entity.newPassword" />
                    </ElFormItem>
                    <ElFormItem prop="confirmPassword" label="确认密码">
                        <ElInput clearable show-password v-model="entity.confirmPassword" />
                    </ElFormItem>
                    <ElFormItem prop="verifyCode" label="验证码">
                        <ElInput clearable v-model="entity.verifyCode">
                            <template #append>
                                <img style="width: 100%;" :src="verifyCodeUrl" class="verify-code"
                                    @click="updateVerifyCode()" />
                            </template>
                        </ElInput>
                    </ElFormItem>
                    <ElFormItem>
                        <ElButton type="primary" :loading="loading" @click="save()">保存</ElButton>
                    </ElFormItem>
                </ElForm>
            </ElMain>
        </ElContainer>
    </div>
</template>

<style scoped lang="scss">
.form {
    max-width: 460px;
}
</style>